layui.use(['ax','admin','form','ztree','table','excel','selectM'], function () {
    var $ = layui.$;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var $ZTree = layui.ztree;
    var table = layui.table;
    var excel = layui.excel;
    var selectM = layui.selectM;
    /**
     *
     */
    var Score = {
        tableId: "dataTable",
        condition: {
            level:2,
            parentId: "",
            city:"",
            county:"",
            year:""
        }
    };

    //查询市
    var pAjax = new $ax(Feng.ctxPath + "/region/selectChildren", function (data) {
        $("#city").empty();
        $("#city").append('<option value="">请选择市</option>')
        $("#city").append(data)
    })
    pAjax.set("regionLevel",2)
    pAjax.set("parentId",16)
    pAjax.start();


    //市登录，初始化区县
    var userLevel = $("#userLevel").val();
    var userCity = $("#userCity").val();
    if(userLevel==2){
        $(".city").hide();
        Score.condition.level = 3;
        var pAjax = new $ax(Feng.ctxPath + "/region/selectChildren", function (data) {
            $("#county").empty();
            $("#county").append('<option value="">请选择区</option>')
            $("#county").append(data)
        })
        pAjax.set("regionLevel", 3)
        pAjax.set("parentId", userCity)
        pAjax.start();
        form.render('select');
    }
    if(userCity!=''){
        Score.condition.city = userCity;
    }




    //点击地图过来的带regionId
    var regionId = $("#regionId").val();
    if(regionId){
        $("#city").val(regionId);
        Score.condition.city = regionId;
        Score.condition.level = 2;

        var pAjax = new $ax(Feng.ctxPath + "/region/selectChildren", function (data) {
            $("#county").empty();
            $("#county").append('<option value="">请选择区</option>')
            $("#county").append(data)
        })
        pAjax.set("regionLevel", 3)
        pAjax.set("parentId", regionId)
        pAjax.start();
    }

    //月份多选
    var monthSelect = selectM({
        //元素容器【必填】
        elem: '#month'
        //候选数据【必填】
        ,data: [{"value":1,"name":"1月"},{"value":2,"name":"2月"},{"value":3,"name":"3月"},{"value":4,"name":"4月"},{"value":5,"name":"5月"},{"value":6,"name":"6月"},{"value":7,"name":"7月"},{"value":8,"name":"8月"},{"value":9,"name":"9月"},{"value":10,"name":"10月"},{"value":11,"name":"11月"},{"value":12,"name":"12月"},]
        ,max:12
        ,width:300
        //候选项数据的键名
        ,field: {idName:'value',titleName:'name'}
        //添加验证
        // ,verify:'required'
        ,tips:"请选择月份,默认为全年"
    });

    form.render('select');

    /**
     * 初始化表格的列
     */
    Score.initColumn = function () {
        return [[
            // {type: 'checkbox'},
            {field: 'data_id', hide: true, sort: true, title: 'id'},
            {field: 'data_name', title: '资料名称',minWidth:'350'},
            {field: 'data_type', title: '资料要求',width:'100'},
            {field: 'data_month', sort: false, title: '时间要求', width:'100',templet: function (d) {
                    return d.data_month + "月底"
            }},
            {field: 'doFlag', title: '完成情况',width:'100'},
            {field: 'file_name', title: '文件名称',templet:"#viewFileTpl"},
            {field: 'statusName', title: '逾期',align:'center',width:'100',templet:function (d) {
                  if(d.statusName == '是'){
                      return  '<span style="color: red;">'+d.statusName+'</span>'
                  }  else if(d.statusName != undefined){
                      return d.statusName
                  } else{
                      return '';
                  }
            }},
            {field: 'base_score', title: '基础分 | 得分',align:'center', templet:function (d) {
                if(d.file_base_score!=null && d.file_base_score!=''){
                    return d.base_score + " | " + '<span style="color: red;">'+d.file_base_score+'</span>'
                }else{
                    return d.base_score + " | " + '<span style="color: red;">'+0+'</span>'
                }
            }},
            {field: 'data_score', title: '评判分',align:'center'},
            {field: 'file_data_score_p', hide:!(userLevel==1), title: '省评判分',align:'center'},
            {field: 'file_data_score_c', hide:!(userLevel==2 || userLevel==1), title: '市评判分',align:'center'},
            {field: 'score_time', title: '评分时间',align:'center'},
            {field: 'scoreUserName', title: '评分人',align:'center'},
            {field: 'hasUpload', title: '操作', toolbar: '#tableBar', minWidth:'170', fixed:'right'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Score.search = function () {
        var queryData = {};
        queryData['condition'] = $("#dataName").val();
        queryData['year'] = Score.condition.year;
        queryData['month'] = monthSelect.values.toString();
        queryData['parentId'] = Score.condition.parentId;
        queryData['level'] = Score.condition.level;
        queryData['city'] = Score.condition.city;
        queryData['county'] = Score.condition.county;
        queryData['score'] = $("#score").val();
        queryData['status'] = $("#status").val();
        table.reload(Score.tableId, {where: queryData});
    };

    $("#btnSearch").click(function () {
        Score.search();
    })

    /**
     * 选择树节点
     */
    Score.onClickJob = function (e, treeId, treeNode) {
        Score.condition.parentId = treeNode.id;
        Score.search();
    }

    Score.refreshTree = function () {
        //初始化左侧树
        var ztree = new $ZTree("jobTree", "/score/tree?year="+Score.condition.year + "&level="+Score.condition.level);
        ztree.bindOnClick(Score.onClickJob);
        ztree.init();
    }


    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Score.tableId,
        id:Score.tableId,
        url: Feng.ctxPath + '/score/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        toolbar: true, //开启头部工具栏
        cols: Score.initColumn(),
        where:{
            'city':Score.condition.city
        }
    });


    //初始化左侧树
    var year = $("#year").val();
    Score.condition.year = year;
    Score.refreshTree();

    /**
     * 更新得分
     * @param fileId
     * @param score
     */
    Score.updateScore = function(fileId,score){
        var pAjax = new $ax(Feng.ctxPath + "/score/updateScore", function (data) {
            if(data=="success"){
                Feng.success("设置分值成功");
            }
        })
        pAjax.set("fileId",fileId)
        pAjax.set("score",score)
        pAjax.start();
    }

    Score.openFile = function (data) {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isIE = userAgent.indexOf("compatible") > -1
        var isChrome = userAgent.indexOf("Chrome") > -1
            && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
        if(isIE){
            var word = new ActiveXObject("Excel.Application");
            word.Visible = true;
            word.Documents.Open(Feng.ctxPath + data.file_path);
        }else{
            window.open(Feng.ctxPath + data.file_path);
        }
    }

    Score.toScore = function(data){
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '评分',
            area:['400px','500px'],
            content: Feng.ctxPath + '/score/toScore?fileId='+data.file_id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Score.tableId);
            }
        });
    }
    
    Score.scoreLog = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '评分记录',
            area:['900px','600px'],
            content: Feng.ctxPath + '/score/scoreLogIndex?fileId='+data.file_id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Score.tableId);
            }
        });
    }


    // 工具条点击事件
    table.on('tool(' + Score.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'score') {
            Score.toScore(data);
        }else if(layEvent === 'viewFile'){
            //查看文件
            Score.openFile(data);
        }else if(layEvent==='scoreLog'){
            Score.scoreLog(data);
        }
    });

    form.on('select(year)',function (data) {
        Score.condition.year = data.value;
        //重新初始化树
        Score.refreshTree();
        //重新查询
        Score.condition.parentId = 0;
        Score.search()
    })

    form.on('select(city)', function (data) {
        Score.condition.city = data.value;
        Score.condition.level = 2;
        Score.condition.county = null;
        Score.refreshTree()
        var pAjax = new $ax(Feng.ctxPath + "/region/selectChildren", function (data) {
            $("#county").empty();
            $("#county").append('<option value="">请选择区</option>')
            $("#county").append(data)
        })
        pAjax.set("regionLevel", 3)
        pAjax.set("parentId", Score.condition.city)
        pAjax.start();
        form.render('select');
    });

    form.on('select(county)', function (data) {
        Score.condition.county = data.value;
        if(data.value==""){
            Score.condition.level = 2;
        }else{
            Score.condition.level = 3;
        }
        Score.refreshTree()
    })

    /**
     * 导入完成的任务
     */
    $("#btnImport").click(function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '导入完成的任务',
            content: Feng.ctxPath + '/score/toImport',
            end: function () {
                admin.getTempData('formOk') && table.reload(Score.tableId);
            }
        });
    })

    //导出Excel表格
    $('#exportExcel').on('click', function(){
        var ajax = new $ax(Feng.ctxPath + "/score/exportExcel", function (data) {
            // 重点！！！如果后端给的数据顺序和映射关系不对，请执行梳理函数后导出
            data = excel.filterExportData(data, [
                'cityName'
                ,'countyName'
                ,'data_name'
                ,'data_type'
                ,'data_month'
                ,'doFlag'
                ,'statusName'
                ,'base_score'
                ,'file_base_score'
                ,'data_score'
                ,'file_data_score_p'
                ,'file_data_score_c'
                ,'score_time'
            ]);
            // 重点2！！！一般都需要加一个表头，表头的键名顺序需要与最终导出的数据一致
            data.unshift({ cityName:"市级单位",countyName:"区级单位",data_name: "资料名称", data_type: "资料要求",data_month: "时间要求",doFlag: '完成情况', statusName: "逾期情况",
                base_score: "基础分",file_base_score:"基础分得分",data_score:"评判分",file_data_score_p:"省评判分",file_data_score_c:"市自评得分",score_time:"评分时间"});

            // 2. 调用设置样式的函数，传入设置的范围，支持回调
            excel.setExportCellStyle(data, 'A1:L1', {
                s: {
                    font: { bold:true, fgColor: { rgb: "FF0000" } },
                    alignment: {
                        horizontal: 'center',
                        vertical: 'center'
                    }
                }
            }, function(cell, newCell, row, config, currentRow, currentCol, fieldKey) {
                // 回调参数，cell:原有数据，newCell:根据批量设置规则自动生成的样式，row:所在行数据，config:传入的配置,currentRow:当前行索引,currentCol:当前列索引，fieldKey:当前字段索引
                return (currentRow === 0) ? newCell : cell;// 第一行表头加粗
            } );

            //设置表格宽度
            var colConf = excel.makeColConfig({
                'A': 80,
                'B': 80,
                'C': 200,
                'D': 80,
                'E': 80,
            }, 100);
            //var date = new Date();
            excel.exportExcel(data,'评分列表.xlsx', 'xlsx', {
                extend: {
                    '!cols': colConf
                }
            });
        }, function (data) {
            Feng.error("导出Excel失败！" + data.responseJSON.message + "!");
        });
        ajax.set("condition",$("#dataName").val());
        ajax.set("year",$("#year").val());
        ajax.set("parentId",Score.condition.parentId);
        ajax.set("level", Score.condition.level);
        ajax.set("city", Score.condition.city);
        ajax.set("county", Score.condition.county);
        ajax.set("score", $("#score").val());
        ajax.set("status", $("#status").val());
        ajax.start();
    });

    //导出部门需要评分的任务
    $("#deptExport").click(function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '按部门导出各个地市区县已完成任务',
            content: Feng.ctxPath + '/score/toDeptExport',
            end: function () {
                admin.getTempData('formOk') && table.reload(Score.tableId);
            }
        });
    })

    //导出部门评分
    $("#deptScoreExport").click(function () {
        window.location.href = Feng.ctxPath + "/score/exportScoreByDept";
    })
    //导入部门评分
    $("#deptScoreImport").click(function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '导入部门评分',
            content: Feng.ctxPath + '/score/toImportDeptScore',
            end: function () {
                admin.getTempData('formOk') && table.reload(Score.tableId);
            }
        });
    })

})